// src/containers/InterviewPrep/index.jsx - 修复后的面试准备组件
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Upload, FileText, Briefcase, ArrowRight, AlertCircle } from 'lucide-react'
import { api, utils } from '../../utils/api' // 导入API工具
import './style.css'

const InterviewPrep = () => {
  const navigate = useNavigate()
  const [formData, setFormData] = useState({
    jobPosition: '',
    resumeFile: null
  })
  const [dragActive, setDragActive] = useState(false)
  const [isUploading, setIsUploading] = useState(false)
  const [errors, setErrors] = useState({})

  // 常见职位选项
  const commonPositions = [
    '软件工程师', '前端开发工程师', '后端开发工程师', '全栈开发工程师',
    '产品经理', '数据分析师', '数据科学家', '算法工程师',
    '市场营销专员', '销售代表', '人力资源专员', '财务分析师',
    'UI/UX设计师', '项目经理', '运营专员', '测试工程师'
  ]

  const handlePositionChange = (e) => {
    setFormData(prev => ({
      ...prev,
      jobPosition: e.target.value
    }))
    if (errors.jobPosition) {
      setErrors(prev => ({
        ...prev,
        jobPosition: ''
      }))
    }
  }

  const handleDrag = (e) => {
    e.preventDefault()
    e.stopPropagation()
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true)
    } else if (e.type === "dragleave") {
      setDragActive(false)
    }
  }

  const handleDrop = (e) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFileSelect(e.dataTransfer.files[0])
    }
  }

  const handleFileSelect = (file) => {
    // 使用API工具验证文件
    if (!utils.isValidImageFile(file)) {
      setErrors(prev => ({
        ...prev,
        resumeFile: '只支持 JPG、PNG 格式的文件'
      }))
      return
    }
    
    if (!utils.isValidFileSize(file, 10 * 1024 * 1024)) { // 10MB
      setErrors(prev => ({
        ...prev,
        resumeFile: '文件大小不能超过 10MB'
      }))
      return
    }
    
    setFormData(prev => ({
      ...prev,
      resumeFile: file
    }))
    
    if (errors.resumeFile) {
      setErrors(prev => ({
        ...prev,
        resumeFile: ''
      }))
    }
  }

  const handleFileInputChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      handleFileSelect(e.target.files[0])
    }
  }

  const validateForm = () => {
    const newErrors = {}
    
    if (!formData.jobPosition.trim()) {
      newErrors.jobPosition = '请输入或选择应聘职位'
    }
    
    if (!formData.resumeFile) {
      newErrors.resumeFile = '请上传简历文件'
    }
    
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (!validateForm()) {
      return
    }
    
    setIsUploading(true)
    
    try {
      // 调用API上传简历
      const result = await api.uploadResume(formData.jobPosition, formData.resumeFile)
      
      console.log('上传成功:', result)
      
      // 跳转到身份验证页面
      navigate(`/verify/${result.session_id}`)
      
    } catch (error) {
      console.error('上传错误:', error)
      setErrors({ submit: '上传失败，请重试' })
    } finally {
      setIsUploading(false)
    }
  }

  return (
    <div className="prep-interview-prep">
      <div className="prep-container">
        <div className="prep-header">
          <h1>面试准备</h1>
          <p>请填写面试信息并上传您的简历</p>
        </div>
        
        <form onSubmit={handleSubmit} className="prep-form">
          {/* 职位输入 */}
          <div className="prep-form-section">
            <label className="prep-form-label">
              <Briefcase size={20} />
              应聘职位
            </label>
            <input
              type="text"
              value={formData.jobPosition}
              onChange={handlePositionChange}
              placeholder="请输入应聘职位，如：软件工程师"
              className={`prep-form-input ${errors.jobPosition ? 'prep-error' : ''}`}
              list="positions"
            />
            <datalist id="positions">
              {commonPositions.map(position => (
                <option key={position} value={position} />
              ))}
            </datalist>
            {errors.jobPosition && (
              <div className="prep-error-message">
                <AlertCircle size={16} />
                {errors.jobPosition}
              </div>
            )}
            
            <div className="prep-common-positions">
              <span className="prep-positions-label">常见职位：</span>
              <div className="prep-position-tags">
                {commonPositions.slice(0, 8).map(position => (
                  <button
                    key={position}
                    type="button"
                    className={`prep-position-tag ${formData.jobPosition === position ? 'prep-active' : ''}`}
                    onClick={() => setFormData(prev => ({ ...prev, jobPosition: position }))}
                  >
                    {position}
                  </button>
                ))}
              </div>
            </div>
          </div>
          
          {/* 简历上传 */}
          <div className="prep-form-section">
            <label className="prep-form-label">
              <FileText size={20} />
              简历文件
            </label>
            
            <div
              className={`prep-upload-area ${dragActive ? 'prep-drag-active' : ''} ${errors.resumeFile ? 'prep-error' : ''}`}
              onDragEnter={handleDrag}
              onDragLeave={handleDrag}
              onDragOver={handleDrag}
              onDrop={handleDrop}
            >
              <input
                type="file"
                id="resume-upload"
                accept=".jpg,.jpeg,.png"
                onChange={handleFileInputChange}
                className="prep-file-input"
              />
              
              {formData.resumeFile ? (
                <div className="prep-file-selected">
                  <FileText size={48} className="prep-file-icon" />
                  <div className="prep-file-info">
                    <p className="prep-file-name">{formData.resumeFile.name}</p>
                    <p className="prep-file-size">
                      {utils.formatFileSize(formData.resumeFile.size)}
                    </p>
                  </div>
                  <button
                    type="button"
                    className="prep-change-file-btn"
                    onClick={() => setFormData(prev => ({ ...prev, resumeFile: null }))}
                  >
                    重新选择
                  </button>
                </div>
              ) : (
                <div className="prep-upload-prompt">
                  <Upload size={48} className="prep-upload-icon" />
                  <p className="prep-upload-title">拖拽文件到此处或点击上传</p>
                  <p className="prep-upload-subtitle">支持 JPG、PNG 格式，最大 10MB</p>
                  <label htmlFor="resume-upload" className="prep-upload-btn">
                    选择文件
                  </label>
                </div>
              )}
            </div>
            
            {errors.resumeFile && (
              <div className="prep-error-message">
                <AlertCircle size={16} />
                {errors.resumeFile}
              </div>
            )}
          </div>
          
          {/* 提交按钮 */}
          <div className="prep-form-actions">
            {errors.submit && (
              <div className="prep-error-message prep-submit-error">
                <AlertCircle size={16} />
                {errors.submit}
              </div>
            )}
            
            <button
              type="submit"
              className="prep-submit-btn"
              disabled={isUploading}
            >
              {isUploading ? (
                <div className="prep-loading-spinner"></div>
              ) : (
                <>
                  继续进行身份验证
                  <ArrowRight size={20} />
                </>
              )}
            </button>
          </div>
        </form>
        
        <div className="prep-tips">
          <h3>💡 面试小贴士</h3>
          <ul>
            <li>确保简历信息完整、准确</li>
            <li>准备好摄像头和麦克风</li>
            <li>选择安静、光线良好的环境</li>
            <li>建议使用 Chrome 或 Edge 浏览器</li>
          </ul>
        </div>
      </div>
    </div>
  )
}

export default InterviewPrep